<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>摄像头捕获与时间显示</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .camera-container {
                @apply relative w-full max-w-4xl mx-auto aspect-video bg-dark rounded-xl overflow-hidden shadow-2xl;
            }
            .time-display {
                @apply absolute bottom-4 right-4 bg-dark/80 text-white px-3 py-2 rounded-lg backdrop-blur-sm font-mono text-lg md:text-xl;
            }
            .btn-capture {
                @apply bg-primary hover:bg-primary/90 text-white font-bold py-3 px-6 rounded-full shadow-lg transform transition-all duration-300 hover:scale-105 active:scale-95 focus:outline-none focus:ring-4 focus:ring-primary/50;
            }
            .btn-download {
                @apply bg-secondary hover:bg-secondary/90 text-white font-bold py-2 px-4 rounded-lg shadow-md transform transition-all duration-300 hover:scale-105 active:scale-95 focus:outline-none;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-light to-gray-200 min-h-screen font-inter flex flex-col items-center justify-center p-4">
    <header class="mb-8 text-center">
        <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold text-dark mb-2">摄像头捕获工具</h1>
        <p class="text-gray-600 text-lg">实时显示摄像头画面与北京时间，支持拍照保存</p>
    </header>
    
    <main class="w-full max-w-5xl">
        <!-- 摄像头容器 -->
        <div class="camera-container mb-8">
            <video id="video" class="w-full h-full object-cover" autoplay playsinline></video>
            <canvas id="canvas" class="hidden absolute inset-0 w-full h-full"></canvas>
            <div id="timeDisplay" class="time-display">
                <span id="currentTime"></span>
            </div>
        </div>
        
        <!-- 控制按钮区域 -->
        <div class="flex flex-col sm:flex-row items-center justify-center gap-4 mb-8">
            <button id="startBtn" class="btn-capture flex items-center gap-2">
                <i class="fa fa-video-camera"></i> 启动摄像头
            </button>
            <button id="captureBtn" class="btn-capture bg-red-500 hover:bg-red-600 flex items-center gap-2" disabled>
                <i class="fa fa-camera"></i> 拍照
            </button>
            <button id="downloadBtn" class="btn-download hidden flex items-center gap-2">
                <i class="fa fa-download"></i> 保存到桌面
            </button>
        </div>
        
        <!-- 预览区域 -->
        <div id="previewContainer" class="hidden mt-8 bg-white p-4 rounded-xl shadow-lg">
            <h2 class="text-xl font-semibold text-dark mb-4">照片预览</h2>
            <div class="flex justify-center">
                <img id="previewImage" class="max-w-full max-h-[400px] rounded-lg shadow-md" alt="拍摄的照片预览">
            </div>
        </div>
    </main>
    
    <footer class="mt-auto text-center text-gray-500 text-sm">
        <p>© 2023 摄像头捕获工具 | 使用HTML5、Tailwind CSS和JavaScript构建</p>
    </footer>

    <script>
        // 获取DOM元素
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const startBtn = document.getElementById('startBtn');
        const captureBtn = document.getElementById('captureBtn');
        const downloadBtn = document.getElementById('downloadBtn');
        const previewContainer = document.getElementById('previewContainer');
        const previewImage = document.getElementById('previewImage');
        const currentTimeEl = document.getElementById('currentTime');
        
        // 上下文和流变量
        let stream = null;
        const ctx = canvas.getContext('2d');
        
        // 更新北京时间
        function updateBeijingTime() {
            // 创建当前时间对象
            const now = new Date();
            
            // 转换为北京时间 (UTC+8)
            const beijingTime = new Date(now.getTime() + (8 * 60 * 60 * 1000));
            
            // 格式化时间
            const options = { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit', 
                minute: '2-digit', 
                second: '2-digit',
                hour12: false,
                timeZone: 'Asia/Shanghai'
            };
            
            const formattedTime = beijingTime.toLocaleString('zh-CN', options);
            currentTimeEl.textContent = formattedTime;
        }
        
        // 启动摄像头
        async function startCamera() {
            try {
                // 获取用户媒体设备
                stream = await navigator.mediaDevices.getUserMedia({ 
                    video: { 
                        width: { ideal: 1920 },
                        height: { ideal: 1080 },
                        facingMode: 'environment' // 优先使用后置摄像头
                    } 
                });
                
                // 将流设置为video元素的源
                video.srcObject = stream;
                
                // 启用拍照按钮
                captureBtn.disabled = false;
                
                // 更改按钮文本
                startBtn.innerHTML = '<i class="fa fa-stop"></i> 关闭摄像头';
                startBtn.classList.remove('bg-primary');
                startBtn.classList.add('bg-gray-500');
                
                // 调整canvas尺寸与视频一致
                video.addEventListener('loadedmetadata', () => {
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                });
                
            } catch (err) {
                console.error('启动摄像头失败:', err);
                alert('无法访问摄像头。请确保您已授予摄像头权限，并且没有其他应用正在使用摄像头。');
            }
        }
        
        // 停止摄像头
        function stopCamera() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                stream = null;
            }
            
            // 禁用拍照按钮
            captureBtn.disabled = true;
            
            // 隐藏预览和下载按钮
            previewContainer.classList.add('hidden');
            downloadBtn.classList.add('hidden');
            
            // 更改按钮文本
            startBtn.innerHTML = '<i class="fa fa-video-camera"></i> 启动摄像头';
            startBtn.classList.remove('bg-gray-500');
            startBtn.classList.add('bg-primary');
        }
        
        // 拍照功能
        function capturePhoto() {
            if (!stream) return;
            
            // 在canvas上绘制当前视频帧
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            // 获取图片数据URL
            const imageDataUrl = canvas.toDataURL('image/jpeg');
            
            // 显示预览
            previewImage.src = imageDataUrl;
            previewContainer.classList.remove('hidden');
            
            // 显示下载按钮
            downloadBtn.classList.remove('hidden');
            downloadBtn.onclick = () => downloadPhoto(imageDataUrl);
            
            // 添加拍照动画效果
            canvas.classList.remove('hidden');
            canvas.style.opacity = '0';
            canvas.style.transition = 'opacity 0.5s';
            
            setTimeout(() => {
                canvas.style.opacity = '1';
            }, 10);
            
            setTimeout(() => {
                canvas.style.opacity = '0';
                setTimeout(() => {
                    canvas.classList.add('hidden');
                }, 500);
            }, 1000);
        }
        
        // 下载照片
        function downloadPhoto(imageDataUrl) {
            // 创建一个a标签用于下载
            const link = document.createElement('a');
            
            // 设置文件名（包含时间戳）
            const now = new Date();
            const fileName = `photo_${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2,'0')}${now.getDate().toString().padStart(2,'0')}_${now.getHours().toString().padStart(2,'0')}${now.getMinutes().toString().padStart(2,'0')}${now.getSeconds().toString().padStart(2,'0')}.jpg`;
            
            link.download = fileName;
            link.href = imageDataUrl;
            
            // 触发下载
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 显示下载成功提示
            alert('照片已保存到您的下载文件夹！');
        }
        
        // 事件监听
        startBtn.addEventListener('click', () => {
            if (stream) {
                stopCamera();
            } else {
                startCamera();
            }
        });  
        captureBtn.addEventListener('click', capturePhoto);
        
        // 初始化时间显示并每秒更新
        updateBeijingTime();
        setInterval(updateBeijingTime, 1000);
    </script>
</body>
</html>
